package com.cwg.dict.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;

import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.ynu.sei.dict.plugin.stardict.StarDictReader;

public class LoadHelper {

	private Logger	logger	= LoggerFactory.getLogger(LoadHelper.class);

	protected String getDicName(File dictDir) {
		assert dictDir.isDirectory() : dictDir.getAbsolutePath() + "is not a directory";
		String extention = ".ifo";
		FilenameFilter filter = new SuffixFileFilter(extention);
		for (File file : dictDir.listFiles(filter)) {
			String name = StringUtils.substringBefore(file.getName(), extention);
			logger.debug("get dic name [{}] from [{}]", name, dictDir.getAbsolutePath());
			return name;
		}
		return "";
	}

	protected StarDictReader getDictQueryService(File dir) {
		try {
			logger.info("load dictionary [{}] from [{}]", getDicName(dir), dir.getAbsolutePath());
			return new StarDictReader(dir.getAbsolutePath(), getDicName(dir));
		} catch (FileNotFoundException e) {
			logger.warn("load dictionary fail at " + dir.getAbsolutePath(), e);
			return null;
		}
	}
}
